package com.ganee.agora.view

import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.core.content.withStyledAttributes
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.jzvd.Jzvd
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bigkoo.convenientbanner.ConvenientBanner
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator
import com.bigkoo.convenientbanner.holder.Holder
import com.bigkoo.convenientbanner.listener.OnPageChangeListener
import com.braintreepayments.api.dropin.DropInActivity
import com.braintreepayments.api.dropin.DropInRequest
import com.braintreepayments.api.dropin.DropInResult
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.ganee.agora.R
import com.ganee.agora.adapter.DetailCommentAdapter
import com.ganee.agora.adapter.DetailRecommendAdapter
import com.ganee.agora.event.CommentEvent
import com.ganee.agora.model.*
import com.ganee.agora.utils.GlideEngine
import com.ganee.agora.utils.ImgUtils
import com.ganee.agora.viewmodel.DetailViewModel
import com.ganee.agora.widget.player.MyVideoPlayer
import com.ganee.baselib.arouter.Constance
import com.ganee.baselib.httprequest.utils.ToastUtil
import com.ganee.baselib.mvvmlibrary.base.BaseActivity
import com.google.gson.Gson
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import kotlinx.android.synthetic.main.activity_detail_new.*
import kotlinx.android.synthetic.main.detail_headview_content.*
import kotlinx.android.synthetic.main.toolbar_with_logo.*
import okhttp3.MediaType
import okhttp3.RequestBody
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONException
import org.json.JSONObject

@Route(path = Constance.ACTIVITY_URL_HOME_DETAIL)
class DetailActivity : BaseActivity<DetailViewModel>(), View.OnClickListener {

    @JvmField
    @Autowired(name = "activeId")
    var activeId: String? = null

    private val localImages: MutableList<BannerEntity> = mutableListOf()
    var convenientBanner:ConvenientBanner<BannerEntity>? = null
    private var mAdapter: DetailRecommendAdapter? = null
    private var mCommentAdapter: DetailCommentAdapter? = null
    private val mList = mutableListOf<InsertActivityEntity>()
    private val mCommentList = mutableListOf<CommentEntity>()
    private var clientToken: String? = null
    private var orderId: String? = null
    private var collectFlag:Boolean = false
    private var entity:DetailEntity? = null

    override fun getViewModel(): DetailViewModel {
        return ViewModelProviders.of(this@DetailActivity).get(DetailViewModel::class.java)
    }

    private val footerView:View
        get(){
            val view = LayoutInflater.from(this).inflate(R.layout.tidbits_footer_view,detailTidbitsRecyclerView!!.parent as ViewGroup,false)
            val rl = view.findViewById<RelativeLayout>(R.id.tidbits_rl) as RelativeLayout
            rl.setOnClickListener{
                initCommentIntent()
            }
            return view
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_detail_new)
        ARouter.getInstance().inject(this)
        EventBus.getDefault().register(this)
        initView()
        initRequestData()
    }

    private fun bannerList(){

        //自定义你的Holder，实现更多复杂的界面，不一定是图片翻页，其他任何控件翻页亦可。
        convenientBanner!!.setPages(
                object :CBViewHolderCreator {
                    override fun createHolder(itemView: View): LocalImageHolderView {
                        return LocalImageHolderView(itemView)
                    }

                    override fun getLayoutId(): Int {
                        return R.layout.item_localimage
                    }
                }, localImages) //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(intArrayOf(R.drawable.indicator_grey, R.drawable.indicator_yellow))
                //.setOnItemClickListener(this);
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setOnPageChangeListener(object : OnPageChangeListener {
                    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {}
                    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {}
                    override fun onPageSelected(index: Int) {
                        Jzvd.releaseAllVideos()
                    }
                })

    }

    private fun initView() {
        toolbarIvReturn.setOnClickListener(this)
        detail_tv_register.setOnClickListener(this)
        detail_content_iv_collect!!.setOnClickListener(this)
        detail_content_iv_invite!!.setOnClickListener(this)
        detail_content_iv_report!!.setOnClickListener(this)
        
        convenientBanner = findViewById(R.id.convenientBanner) as ConvenientBanner<BannerEntity>
        recommendRecyclerView.setHasFixedSize(true)
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        recommendRecyclerView.layoutManager = layoutManager

        detailTidbitsRecyclerView.setHasFixedSize(true)
        val lm = LinearLayoutManager(this)
        lm.orientation = LinearLayoutManager.HORIZONTAL
        detailTidbitsRecyclerView.layoutManager = lm
        
        mAdapter = DetailRecommendAdapter(mList)
        recommendRecyclerView.adapter = mAdapter

        mCommentAdapter = DetailCommentAdapter(mCommentList)
        mCommentAdapter!!.addFooterView(footerView)
        mCommentAdapter!!.onItemClickListener = BaseQuickAdapter.OnItemClickListener{ adapter, view, position ->
            initCommentIntent()
        }
        detailTidbitsRecyclerView.adapter = mCommentAdapter
        
    }

    private fun initRequestData() {
        val requestData = JSONObject()
        try {
            requestData.put("activeId", activeId)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        val requestBody = RequestBody.create(MediaType.parse("application/json"), requestData.toString())
        viewModel.getDetailInfo(requestBody)
        viewModel.getCommentList(requestBody)
        viewModel.getRecommendList()


        viewModel.detail.observe(this, Observer<DetailEntity> {
            entity = it
            initData()
        })

        viewModel.commentList.observe(this, Observer<List<CommentEntity>> {
            mCommentList.clear()
            mCommentList.addAll(it)
            mCommentAdapter!!.notifyDataSetChanged()
        })
        viewModel.recommendList.observe(this, Observer<List<InsertActivityEntity>> {
            mList.clear()
            mList.addAll(it)
            mAdapter!!.notifyDataSetChanged()
        })

    }

    private fun initData() {

        detail_tv_title!!.text = entity!!.eventTitle
        detail_tv_user!!.text = "by " + entity!!.host
        detail_tv_ticket!!.text = entity!!.ticketLeft
        if (!TextUtils.isEmpty(entity!!.score)) {
            detail_content_ratingbar.rating = entity!!.score!!.toFloat()
        }
        detail_tv_repeat!!.text = entity!!.roundType
        var start:String? = ""
        var end:String? = ""
        if (null != entity!!.startTime) {
            start = getTime(entity!!.startTime!!)
        }
        if(null != entity!!.endTime){
            end = getTime(entity!!.endTime!!)
        }
        detail_tv_time!!.text = "$start - $end"
        detail_tv_address!!.text = entity!!.location
        detail_tv_des!!.text = entity!!.about
       if (entity!!.amount != null && entity!!.amount!!.toDouble() > 0){
           detail_tv_price!!.text = "$" + entity!!.amount
       } else {
           detail_tv_price!!.text = "Free"
       }
        detail_tv_register.isEnabled = !entity!!.enrollStatus

        collectFlag = entity!!.collectStatus
        for(file in entity!!.fileList){
            if ("02" == file.fileType){
                localImages.add(BannerEntity("video",file.filePath))
            }
        }
        for(file in entity!!.fileList){
            if ("01" == file.fileType){
                localImages.add(BannerEntity("pic",file.filePath))
            }
        }
        bannerList()
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.toolbarIvReturn -> {
                finish()
            }
            R.id.detail_tv_register -> {
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_REGISTER_INFO)
                        .withString("activeId",activeId)
                        .withString("eventTitle",detail_tv_title.text.toString())
                        .withString("email",entity!!.email)
                        .withString("time",detail_tv_time.text.toString())
                        .withString("host",detail_tv_user.text.toString())
                        .withString("activePic",entity!!.activePic)
                        .withString("tickets",entity!!.ticketLeft)
                        .navigation(this@DetailActivity)
//                initRequestClientToken()
            }
            R.id.detail_content_iv_report -> {
                ToastUtil.showToast("More features are under development")
            }
            R.id.detail_content_iv_invite -> {
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_INVITE)
                        .withString("activeId",activeId)
                        .navigation(this@DetailActivity)
            }
            R.id.detail_content_iv_collect -> {
                val requestData = JSONObject()
                try {
                    requestData.put("activeId", activeId)
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
                val requestBody = RequestBody.create(MediaType.parse("application/json"), requestData.toString())
                if (collectFlag) {
                    viewModel.postCollect(requestBody)
                    collectFlag = !collectFlag
                } else {
                    viewModel.postCancelCollect(requestBody)
                    collectFlag = !collectFlag
                }
            }
        }
    }

    private fun initCommentIntent() {
        ARouter.getInstance()
                .build(Constance.ACTIVITY_URL_COMMENT)
                .withString("activeId",activeId)
                .navigation(this@DetailActivity)
    }
    private fun getTime(time:String):String{
        val month = time.substring(4, 6).toInt()
        val day = time.substring(6, 8)
        val hour = time.substring(8, 10)
        val minute = time.substring(10, 12)
        var mMonth: String? = null
        when (month) {
            1 -> mMonth = "Jan"
            2 -> mMonth = "Feb"
            3 -> mMonth = "Mar"
            4 -> mMonth = "Apr"
            5 -> mMonth = "May"
            6 -> mMonth = "Jun"
            7 -> mMonth = "Jul"
            8 -> mMonth = "Aug"
            9 -> mMonth = "Sept"
            10 -> mMonth = "Oct"
            11 -> mMonth = "Nov"
            12 -> mMonth = "Dec"
        }
        var mHour: String? = null
        mHour = if (hour.toInt() >= 12) {
            hour + ":" + minute + "pm"
        } else {
            hour + ":" + minute + "am"
        }
        return "$mMonth $day · $mHour"
    }
    private fun initRequestClientToken() {
        val requestData = JSONObject()
        try {
            requestData.put("activeId", activeId)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        val requestBody = RequestBody.create(MediaType.parse("application/json"), requestData.toString())
        viewModel.getClientToken(requestBody)

        viewModel.clientTokenEntity.observe(this, Observer<ClientTokenEntity> {
            clientToken = it.token
            orderId = it.orderId

            val dropInRequest = DropInRequest()
                    .clientToken(clientToken) as DropInRequest
            startActivityForResult(dropInRequest.getIntent(this), REQUEST_CODE)
        })
    }



    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                val result = data!!.getParcelableExtra (DropInResult.EXTRA_DROP_IN_RESULT) as DropInResult
                // use the result to update your UI and send the payment method nonce to your server
                val payRequestBody = PayRequestBody(result.paymentMethodNonce!!.nonce,orderId)
                val body = Gson().toJson(payRequestBody)
                val requestBody = RequestBody.create(MediaType.parse("application/json"), body)
                viewModel.postExecutePay(requestBody)
            } else if (resultCode == RESULT_CANCELED) {
                // the user canceled
            } else {
                // handle errors here, an exception may be available in
                val error = data!!.getSerializableExtra (DropInActivity.EXTRA_ERROR) as Exception
            }
        }
    }

    private var imageView: ImageView? = null
    var player: MyVideoPlayer? = null
    inner class LocalImageHolderView(itemView:View): Holder<BannerEntity>(itemView) {
        override fun updateUI(data: BannerEntity?) {
            if ("pic" == data!!.type) {
                imageView!!.visibility = View.VISIBLE
                player!!.visibility = View.GONE
                Glide.with(this@DetailActivity)
                        .load(data.url)
                        .into(imageView!!)
            } else if ("video" == data.type) {
                imageView!!.visibility = View.GONE
                player!!.visibility = View.VISIBLE
                player!!.setUp(data.url,"")
//                val bitmap = ImgUtils.createVideoThumbnail(data.url, MediaStore.Images.Thumbnails.MINI_KIND) as Bitmap
//                player!!.thumbImageView.setImageBitmap(bitmap)
                player!!.backButton.visibility = View.GONE
            }
        }

        override fun initView(itemView: View?) {
            imageView = itemView!!.findViewById(R.id.imageView)
            player = itemView.findViewById(R.id.player)
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun refreshCommentData(event:CommentEvent){
        val requestData = JSONObject()
        try {
            requestData.put("activeId", activeId)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        val requestBody = RequestBody.create(MediaType.parse("application/json"), requestData.toString())
        viewModel.getCommentList(requestBody)

        viewModel.commentList.observe(this, Observer<List<CommentEntity>> {
            mCommentList.clear()
            mCommentList.addAll(it)
            mCommentAdapter!!.notifyDataSetChanged()
        })
    }
    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    override fun onPause() {
        super.onPause()
        Jzvd.releaseAllVideos()
    }

    override fun onBackPressed() {
        if (Jzvd.backPress()) {
            return
        }
        super.onBackPressed()
    }

    companion object {
        internal const val REQUEST_CODE = 110
    }
}

